package ipc.project;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.View.OnClickListener;

public class StartActivity extends Activity implements OnClickListener {
	private Context context = this;
	private User user = new User();
	public SharedPreferences settings;

	TextView loginText;
	TextView passwordText;
	CheckBox ChckbxVisiblePassword;
	Button BtnLogin;
	Button BtnRegister;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		settings = getSharedPreferences(Service.SETTINGS, MODE_PRIVATE);
		user = new User(settings);
		if (user.signIn()) {
			((App) getApplication()).setUser(user);
			startActivity(new Intent(context, MainActivity.class));
			finish();
		}
		
		setContentView(R.layout.login_screen);
		
		loginText = (TextView) findViewById(R.id.txtInputLogin);
		passwordText = (TextView) findViewById(R.id.txtInputPassword);

		ChckbxVisiblePassword = (CheckBox) findViewById(R.id.CheckBoxOfVisibility);
		ChckbxVisiblePassword.setOnClickListener(this);

		BtnLogin = (Button) findViewById(R.id.ButtonLogin);
		BtnLogin.setOnClickListener(this);

		BtnRegister = (Button) findViewById(R.id.LoginBtnRegister);
		BtnRegister.setOnClickListener(this);

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.CheckBoxOfVisibility:
			if (ChckbxVisiblePassword.isChecked()) {
				passwordText.setTransformationMethod(null);
			} else {
				passwordText.setTransformationMethod(new PasswordTransformationMethod());
			}
			break;
		case R.id.ButtonLogin:
			BtnLogin.setEnabled(false);
			BtnRegister.setEnabled(false);
			user = new User(loginText.getText().toString(), passwordText.getText().toString());
			if (user.signIn()) {
				user.saveData(settings);
				((App) getApplication()).setUser(user);
				startActivity(new Intent(context, MainActivity.class));
				finish();
			} else {
				BtnLogin.setEnabled(true);
				BtnRegister.setEnabled(true);
			}
			break;
		case R.id.LoginBtnRegister:
			user = new User(loginText.getText().toString(), passwordText.getText().toString());
			BtnLogin.setEnabled(false);
			BtnRegister.setEnabled(false);
			if (user.signUp()) {
				user.saveData(settings);
				((App) getApplication()).setUser(user);
				startActivity(new Intent(context, MainActivity.class));
				finish();
			} else {
				BtnLogin.setEnabled(true);
				BtnRegister.setEnabled(true);
			}
			break;
		}
	}

}
